package server

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"stargazer/xnat/xnetc/client"
	"strings"
)

// var mux *Mux

func setResponseHeader(w *http.ResponseWriter, header http.Header) {
	for k, v := range header {
		(*w).Header()[k] = v
	}
}

// XNetHandler : handler used to dispatch the http request
func XNetHandler(w http.ResponseWriter, req *http.Request) {
	path := string([]rune(req.URL.Path)[6:])
	// fmt.Println(path)
	i := strings.Index(path, "/")
	var username string
	var realPath string
	if i == -1 {
		username = path
	} else {
		index := strings.Index(path, "/")
		username = path[:index]
		realPath = path[index:]
		fmt.Println(username)
	}
	httpRequestData := client.HttpRequestData{}
	httpRequestData.Url = realPath
	httpRequestData.Header = req.Header
	httpRequestData.Method = req.Method
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		log.Println(err.Error())
	}
	httpRequestData.Body = body

	ch := make(chan client.HttpResponseData)
	go mux.exchangeHTTPMsg(httpRequestData, username, ch)
	responseData := <-ch
	// buf := new(bytes.Buffer)
	// buf.ReadFrom(response.Body)
	setResponseHeader(&w, responseData.Header)
	w.WriteHeader(responseData.Status)
	w.Write(responseData.Body)
}

func setRouter() {
	http.HandleFunc("/xnet/", XNetHandler)
}

// RunHTTPServer : run the http server which is exposed to the vistor outside of the NAT network
func RunHTTPServer(m *Mux) {
	// mux = m
	setRouter()
	fmt.Println("HTTPServer listening at 8888")
	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
